/*
 * Copyright 2021 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package internal

import (
	"encoding/json"
	"fmt"
	"time"

	log "github.com/sirupsen/logrus"
)

func formateData(readings []byte, topic string) ([]byte, error) {

	var m = make([]map[string]interface{}, 100, 100)

	mq := MqInfo.HostName
	if mq == "rabbitmq" || topic == "kuiper" {
		var data []map[string]interface{}
		err := json.Unmarshal(readings, &data)
		if err != nil {
			log.Error(err)
			return nil, err
		}

		m = data
	} else {
		var data map[string]interface{}
		err := json.Unmarshal(readings, &data)
		if err != nil {
			log.Error(err)
			return nil, err
		}

		m[0] = data
	}

	firstPkt := m[0]
	for key := range firstPkt {
		if key == "readings" {
			fmt.Println("[Formated Data]pkt has proper Readings:", m)
			return readings, nil
		}
	}

	for key := range firstPkt {
		if key == "asset" {
			fmt.Println("[Formated Data]pkt has Asset:", m)
			return arrangeData(m)
		}
	}

	fmt.Println("[Formated Data]pkt is Raw:", m)
	return buildPkt(m)
}

//rearrange data to fit format
func arrangeData(m []map[string]interface{}) ([]byte, error) {
	var fmtDatas []map[string]interface{}

	for _, reading := range m {

		fmtData := make(map[string]interface{})
		readingsData := make(map[string]interface{})

		for key := range reading {
			if key == "asset" {
				fmtData[key] = reading[key]
			} else if key == "timestamp" {
				fmtData[key] = reading[key]
			} else {
				readingsData[key] = reading[key]
			}
		}
		fmtData["readings"] = readingsData
		fmtDatas = append(fmtDatas, fmtData)
	}

	data, err := json.Marshal(fmtDatas)
	if err != nil {
		log.Errorf("Marshling failed: %v", err)
		return nil, err
	}

	return data, nil
}

//build formated data from raw readings
func buildPkt(m []map[string]interface{}) ([]byte, error) {

	var fmtDatas []map[string]interface{}
	fmtData := make(map[string]interface{})

	fmtData["asset"] = ""
	fmtData["timestamp"] = time.Now().String()
	fmtData["readings"] = m

	fmtDatas = append(fmtDatas, fmtData)

	data, err := json.Marshal(fmtDatas)
	if err != nil {
		log.Errorf("Marshling failed: %v", err)
		return nil, err
	}
	return data, nil
}
